﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace CheckProcessService
{
    public partial class CheckProcessService : ServiceBase
    {
        private string configFilePath;
        private System.Timers.Timer timer;

        public CheckProcessService()
        {
            InitializeComponent();
        }

        /*
　　        Windows服务在系统安装后会在注册表的 "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\[ServiceName]"下以服务的ServiceName建1个目录，目录中会有"ImagePath"节，这里保存的就是该服务的安装路径。
        */
        /// <summary>
        /// 获取服务安装路径
        /// </summary>
        /// <param name="ServiceName"></param>
        /// <returns></returns>
        public static string GetWindowsServiceInstallPath(string ServiceName)
        {
            string key = @"SYSTEM\CurrentControlSet\Services\" + ServiceName;
            string path = Registry.LocalMachine.OpenSubKey(key).GetValue("ImagePath").ToString();
            //替换掉双引号   
            path = path.Replace("\"", string.Empty);
            FileInfo fi = new FileInfo(path);
            return fi.Directory.ToString();
        }

        private bool ProcessExist(string processName)
        {
            Process[] processes = Process.GetProcesses();
            foreach (Process p in processes)
            {
                if (p.ProcessName.Equals(processName))
                {
                    return true;
                }
            }
            return false;
        }

        protected override void OnStart(string[] args)
        {
            if (args == null || args.Length < 1)
            {
                configFilePath = GetWindowsServiceInstallPath("CheckProcessService") + "\\check.conf";
            }
            else
            {
                string tmp = args[0];
                if (tmp.IndexOf("://") > 0)
                {
                    configFilePath = tmp;
                }
                else
                {
                    configFilePath = GetWindowsServiceInstallPath("CheckProcessService") + "\\" + tmp;
                }
            }

            timer = new System.Timers.Timer(1000 * int.Parse(ConfigurationManager.AppSettings["timespan"]));
            timer.Elapsed += timer_Elapsed;
            timer.Enabled = true;
            timer.Start();
        }

        void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            using (StreamReader sr = new StreamReader(new FileStream(configFilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))
            {
                string line = sr.ReadLine();
                while (line != null)
                {
                    string[] args = line.Split(new char[] { ',', '，' });
                    if (args.Length > 1)
                    {
                        if (!ProcessExist(args[0]))
                        {
                            Process.Start(args[1]);
                        }
                    }                
                    
                    line = sr.ReadLine();
                }
            }
        }

        protected override void OnStop()
        {
        }
    }
}
